<template>
    <div class="start" v-if="$store.state.pk.status ==='matching'">
        <button type="button" class="btn btn-success"  @click="start_game">开 始 游 戏</button>
    </div>
    <GameGround v-if="$store.state.pk.status ==='playing'" />
    <ResultBoard v-if="$store.state.pk.loser != 'none'" />
</template>
    
<script>
import GameGround from '../../../components/GameGround.vue'
import { useStore } from 'vuex';
import {onMounted, onUnmounted} from 'vue'
import ResultBoard from '../../../components/ResultBoard.vue'
export default{
    components:{
        GameGround,
        ResultBoard
    },
    setup(){
        let socket = null;
        const store = useStore();
        onMounted(()=>{
            const socketUrl = `ws://127.0.0.1:3000/websocket/${store.state.user.token}/`
            socket = new WebSocket(socketUrl);
            console.log(socket);
            store.commit("updateSocket",socket);
            socket.onopen =() =>{
            }
            socket.onmessage= msg =>{
                const data = JSON.parse(msg.data);
                if(data.event==="startFG"){
                    store.commit("updateStatus","playing");
                    store.commit("updateGame",data.game);
                    console.log(data.game);
                }else if(data.event === "f_move"){
                    const game = store.state.pk.game_object;           
                    const [snake0, snake1] = game.snakes;
                    snake0.set_direction(data.a_direction);
                    snake1.set_direction(data.b_direction);
                }else if(data.event === "result"){ 
                    const game = store.state.pk.game_object;           
                    const [snake0, snake1] = game.snakes;
                    if(data.loser === 'all' || data.loser === 'A'){
                        snake0.status = 'die';
                    }
                    if(data.loser === 'all' || data.loser === 'B'){
                        snake1.status = 'die';
                    }
                    store.commit("updateLoser", data.loser);
                    socket.close();
                }
            }
            socket.onclose=()=>{

            }
        })
        const start_game =()=>{
            store.commit("updateMode","friend");
            store.state.user.socket.send(JSON.stringify({
                    event:"start_friend_game",
                }))
        }
        onUnmounted(()=>{
            store.commit("updateStatus","matching");
            socket.close();
        })
        return{
            start_game,
        }
    }
}
</script>

<style scoped>
.start > button{
    margin: 0 auto;
    display:block;
    font-size: 80px;
    font-style: italic;
    padding:20px 100px;
    border-radius: 30px;
}
.start>button:hover{
    font-size: 90px;
    transition: 200ms;
}
.start{
    margin-top: 400px;

}

</style>